/*
 * @describe: ***
 * @version: 1.0
 * @Author: yanghm
 * @Date: 2023-04-07 11:34:56
 * @LastEditors: yanghm
 * @LastEditTime: 2023-04-14 10:36:11
 */
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersistence from 'vuex-persist'
import * as types from './mutation-types'
import { logout, getUserInfo, getToken } from '@/utils/http'

Vue.use(Vuex)

const vuexLocal = new VuexPersistence({
  storage: window.localStorage,
  reducer: state => ({
    token: state.token // 存入localStorage的值
  })
})
const state = {
  token: '', // token
  isGetToken: false, // 是否获取token
  userInfo: {}, // 用户信息
  loginStatus: false, // 登录状态
  loginMessage: ''
}
const mutations = {
  /* 用户登录,获取token */
  [types.USER_GET_TOKEN] (state, info) {
    if (info.result&&info.result.tokenId) {
      state.token = info.result.token // token
      localStorage.token = info.result.token // 把token放入本地存储
      state.isGetToken = true
    } else {
      state.token = ''
      localStorage.token = ''
      state.isGetToken = false
      state.loginMessage = info.message
    }
  },
  /* 用户登录,获取用户信息 */
  [types.USER_GET_USERINFO] (state, info) {
    if (info.code === 0) {
      state.userInfo = info.data || {} // 用户信息
      state.loginStatus = true // 登录状态
    }
  },
  /* 用户退出登录 */
  [types.USER_LOGIN_EXIT](state) {
    state.isGetToken = false
    state.loginStatus = false
    state.token = ''
    state.userInfo = ''
    localStorage.token = ''
  }
}
const actions = {
  /* 用户登录,获取token */
  getUserToken: async({
    commit
  }, params) => {
    let token = await getToken(params) // 获取token
    await commit(types.USER_GET_TOKEN, token)
  },
  /* 获取用户信息 */
  getUserInfo: async({
    commit
  }) => {
    let result = await getUserInfo() // 获取用户信息
    await commit(types.USER_GET_USERINFO, result)
  },
  /* 退出登录 */
  exitSuccess: async({
    commit
  }) => {
    // let result = await logout() // 退出登录
    await commit(types.USER_LOGIN_EXIT)
  }
}
const getters = {
  userToken: state => state.token,
  userInfo: state => state.userInfo,
  isGetToken: state => state.isGetToken,
  loginStatus: state => state.loginStatus
}
const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters,
  plugins: [vuexLocal.plugin]
})
export default store
